package com.reebake.ideal.user.controller.client;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.reebake.ideal.user.client.UserLoginLogClient;
import com.reebake.ideal.user.entity.UserCredential;
import com.reebake.ideal.user.entity.UserLogin;
import com.reebake.ideal.user.entity.UserLoginLogDTO;
import com.reebake.ideal.user.service.UserCredentialService;
import com.reebake.ideal.user.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/client/user/login")
public class UserLoginLogClientController implements UserLoginLogClient {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserCredentialService userCredentialService;
    @Override
    public void log(UserLoginLogDTO userLoginLogDTO) {
        UserLogin userLogin = new UserLogin();
        userLogin.setLoginIp(userLoginLogDTO.getLoginIp());
        userLogin.setLoginLocation(userLoginLogDTO.getLoginLocation());
        userLogin.setLoginTime(userLoginLogDTO.getLoginTime());
        userLogin.setLoginName(userLoginLogDTO.getLoginName());
        userLogin.setDeviceId(userLoginLogDTO.getDeviceId());
        userLogin.setSource(userLoginLogDTO.getSource());
        userLogin.setBrowserName(userLoginLogDTO.getBrowserName());
        userLogin.setBrowserVersion(userLoginLogDTO.getBrowserVersion());
        userLogin.setOsName(userLoginLogDTO.getOsName());
        userLogin.setOsVersion(userLoginLogDTO.getOsVersion());
        userLogin.setUserId(userLoginLogDTO.getUserId());

        userLoginService.save(userLogin);

        UserCredential userCredential = new UserCredential();
        userCredential.setLastLoginIp(userLogin.getLoginIp());
        userCredential.setLastLoginTime(userLogin.getLoginTime());
        LambdaUpdateWrapper<UserCredential> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCredential::getUserId, userLogin.getUserId());
        userCredentialService.update(userCredential, updateWrapper);
    }
}
